package cn.z2huo.knowledge.concurrency.thinkinginjava.section_21_3.syncCodeBlock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class CriticalSection {

    static void testApproaches(BasePairManager pairManager, BasePairManager pairManager2) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        PairManipulator pairManipulator = new PairManipulator(pairManager);
        PairManipulator pairManipulator2 = new PairManipulator(pairManager2);

        PairChecker pairChecker = new PairChecker(pairManager);
        PairChecker pairChecker2 = new PairChecker(pairManager2);

        executorService.execute(pairManipulator);
        executorService.execute(pairManipulator2);

        executorService.execute(pairChecker);
        executorService.execute(pairChecker2);

        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            System.out.println("sleep interrupted");
        }
        System.out.println("pairManipulator: " + pairManipulator);
        System.out.println("pairManipulator2: " + pairManipulator2);
        System.exit(0);
    }

    public static void main(String[] args) {
        BasePairManager pairManager = new PairManager();
        BasePairManager pairManager2 = new PairManager2();
        testApproaches(pairManager, pairManager2);
    }

}
